package com.uenpay.oem.ui.user.info;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.qiyunxin.android.http.common.ImageUtil;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.socks.library.KLog;
import com.uenpay.im.IMApplication;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.ImageSize;
import com.uenpay.im.entities.PersonInfoConstant;
import com.uenpay.im.entities.QYXUserEntity;
import com.uenpay.im.ui.old.activity.area.AreaActivity;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.choosemorepic.PhotoActivity;
import com.uenpay.im.ui.old.activity.choosemorepic.TakePhotoActivity;
import com.uenpay.im.ui.old.activity.personal.ClipImageActivity;
import com.uenpay.im.ui.old.activity.personal.EditInfoActivity;
import com.uenpay.im.ui.old.activity.personal.QRCodeActivity;
import com.uenpay.im.view.PictureShowActivity;
import com.uenpay.im.weight.BottomDialog;
import com.uenpay.oem.MyApplication;
import com.uenpay.oem.R;
import com.uenpay.oem.common.ACacheConstant;
import com.uenpay.oem.common.RxBusEventConstant;
import com.uenpay.oem.data.bean.UserAuthInfo;
import com.uenpay.oem.ui.auth.AuthActivity;
import com.uenpay.oem.ui.main.home.HomeNewFragment;
import com.uenpay.oem.ui.main.my.MyFragment;
import com.uenpay.oem.ui.trans.paycode.PayCodeActivity;
import com.uenpay.util.app.base.BaseActivity;
import com.uenpay.util.common.ACache;
import com.uenpay.util.imageloader.ImageLoader;
import com.uenpay.util.imageloader.ImageLoaderUtil;
import com.uenpay.util.imageloader.transform.GlideRoundTransform;
import com.uenpay.util.rx.CommonEvent;
import com.uenpay.util.rx.RxBus;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.functions.Action1;

/**
 * Author: liulou Date: 2017/6/19. desc:
 */

public class UserInfoActivity extends BaseActivity implements UserInfoContract.View {

    public static final String TAG = "UserInfoActivity";

    private final int CHOOSE_TAKE_PHOTO_REQUEST_CODE = 110;
    private final int CHOOSE_IMAGE_REQUEST_CODE = 111;
    private final int CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE = 112;

    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.rl_avatar_layout)
    RelativeLayout rlAvatarLayout;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.rl_nickname_layout)
    RelativeLayout rlNicknameLayout;
    @BindView(R.id.tv_idcard)
    TextView tvIdcard;
    @BindView(R.id.rl_idcard_layout)
    RelativeLayout rlIdcardLayout;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.rl_phone_layout)
    RelativeLayout rlPhoneLayout;
    @BindView(R.id.tv_real_name)
    TextView tvRealName;
    @BindView(R.id.rl_real_name_layout)
    RelativeLayout rlRealNameLayout;
    @BindView(R.id.rl_qrcode_layout)
    RelativeLayout rlQrcodeLayout;
    @BindView(R.id.tv_area)
    TextView tvArea;
    @BindView(R.id.rl_area_layout)
    RelativeLayout rlAreaLayout;
    @BindView(R.id.tv_email)
    TextView tvEmail;
    @BindView(R.id.rl_email_layout)
    RelativeLayout rlEmailLayout;
    @BindView(R.id.iv_user)
    ImageView iv_user;

    private UserInfoContract.Presenter mUserInfoPresenter;

    private boolean isFromTalk = false;

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_user_info;
    }

    @Override
    public void initView(View view) {
        setTitle("个人信息");

        if (getIntent() != null) {
            isFromTalk = getIntent().getBooleanExtra("is_from_talk", false);
        }
        setPresenter(null);
        mUserInfoPresenter.getPersonInfo();
        String phone = IMApplication.getUserMobilePhone();
        String phone1 = phone.substring(0, 3);
        String phone2 = phone.substring(phone.length() - 4);
        tvPhone.setText(phone1 + "****" + phone2);
        if (MyApplication.getUserAuthInfo() != null) {
            showUserAuthInfo(MyApplication.getUserAuthInfo());
        }
        Observable<CommonEvent> observable = RxBus.$().register(TAG);
        RxBus.$().OnEvent(observable, new Action1<Object>() {
            @Override
            public void call(Object obj) {
                CommonEvent event = (CommonEvent) obj;
                KLog.d(TAG, "CommonEvent --->" + event.getWhat());
                if (event.getWhat() == RxBusEventConstant.EVENT_UPDATE_USER_AUTH_INFO) {
                    mUserInfoPresenter.getPersonInfo();
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void dismissLoading() {

    }

    @Override
    public void setPresenter(Object presenter) {
        mUserInfoPresenter = new UserInfoPresenter(this);
    }

    @Override
    public void showToast(String msg) {

    }

    @Override
    public void showPersonInfo(QYXUserEntity user) {
        String url = APIConfiguration.getAvatarUrlNormal(user.custid, PacketType.PERSONAL);
        ImageLoaderUtil.getInstance().loadImage(this, new ImageLoader.Builder().isCircle(true).url(url).imgView(ivAvatar).build());
        tvNickname.setText(user.nickname);
        tvArea.setText(user.area);
        tvEmail.setText(user.email);
    }

    @Override
    public void showUserAuthInfo(UserAuthInfo info) {
        if (info != null) {
            if (info.getIsReal() == UserAuthInfo.AUTH_TRUE) {
                String name = info.getRealName();
                String name1 = name.substring(0, 1);
                tvRealName.setText(name.replace(name1, "*"));
                rlRealNameLayout.setClickable(false);
                String cerNo = info.getCerNo();

                String cerNo1 = cerNo.substring(0, 6);
                String cerNo2 = cerNo.substring(cerNo.length() - 4);
                tvIdcard.setText(cerNo1 + "********" + cerNo2);
                iv_user.setVisibility(View.GONE);
                rlIdcardLayout.setClickable(false);
            } else {
                tvRealName.setText("前往实名认证");
                rlRealNameLayout.setClickable(true);
                tvIdcard.setText("前往实名认证");
                rlIdcardLayout.setClickable(true);
                iv_user.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void changeAvatar(String url) {
        ImageLoaderUtil.getInstance().loadImage(this, new ImageLoader.Builder().isCache(false).isCircle(true).url(url).imgView(ivAvatar).build());
        RxBus.$().post(MyFragment.TAG, new CommonEvent(RxBusEventConstant.EVENT_AVATAR_CHANGE));
        RxBus.$().post(HomeNewFragment.TAG, new CommonEvent(RxBusEventConstant.EVENT_AVATAR_CHANGE));
    }

    private void updateAvatarDialog() {
        BottomDialog.showBottomDialog(UserInfoActivity.this, getResources().getString(com.uenpay.im.R.string.take_photo), getResources()
                        .getString(com.uenpay.im.R.string.take_image), getResources().getString(com.uenpay.im.R.string.cancel), -1,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        takePhoto();
                    }
                }, new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        pickImage();
                    }
                });

    }

    private void takePhoto() {
        Intent getImageByCamera = new Intent(UserInfoActivity.this, TakePhotoActivity.class);
        ArrayList<ImageSize> size = new ArrayList<ImageSize>();
        size.add(new ImageSize(720, 720, ""));
        Bundle bundle = new Bundle();
        bundle.putSerializable("size", size);
        getImageByCamera.putExtras(bundle);
        startActivityForResult(getImageByCamera, CHOOSE_TAKE_PHOTO_REQUEST_CODE);
    }

    private void pickImage() {
        Intent getImage = new Intent(UserInfoActivity.this, PhotoActivity.class);
        getImage.putExtra("selected_count", 0);
        getImage.putExtra("max_select_count", 1);
        startActivityForResult(getImage, CHOOSE_IMAGE_REQUEST_CODE);
    }

    @OnClick({R.id.iv_avatar, R.id.rl_avatar_layout, R.id.rl_nickname_layout, R.id.rl_idcard_layout, R.id.rl_real_name_layout,
            R.id.rl_qrcode_layout, R.id.rl_area_layout, R.id.rl_email_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_avatar:
                String bigpath = "";
                if (!TextUtils.isEmpty(APIConfiguration.getAvatarUrlBig(IMApplication.getCustId(), PacketType.PERSONAL))) {
                    bigpath = APIConfiguration.getAvatarUrlBig(IMApplication.getCustId(), PacketType.PERSONAL);
                } else {
                    return;
                }
                ArrayList<String> imgs = new ArrayList<String>();
                Intent show = new Intent(UserInfoActivity.this, PictureShowActivity.class);
                show.putExtra("content", bigpath);
                imgs.add(bigpath);
                show.putStringArrayListExtra("imgList", imgs);
                startActivity(show);
                break;
            case R.id.rl_avatar_layout:
                updateAvatarDialog();
                break;
            case R.id.rl_nickname_layout:
                if (isFromTalk) {
                    return;
                }
                Intent intent = new Intent(UserInfoActivity.this, EditInfoActivity.class);
                intent.putExtra("oldStr", tvNickname.getText().toString());
                intent.putExtra("update_type", PersonInfoConstant.updateName);
                startActivityForResult(intent, PersonInfoConstant.updateName);
                break;
            case R.id.rl_idcard_layout:
                Intent authIt = new Intent(UserInfoActivity.this, AuthActivity.class);
                startActivity(authIt);
                break;
            case R.id.rl_real_name_layout:
                Intent authIt1 = new Intent(UserInfoActivity.this, AuthActivity.class);
                startActivity(authIt1);
                break;
            case R.id.rl_qrcode_layout:
                ActivityHandle.startActivity(UserInfoActivity.this, QRCodeActivity.class, null, -1);
                break;
            case R.id.rl_area_layout:
                Intent areaIt = new Intent(UserInfoActivity.this, AreaActivity.class);
                startActivityForResult(areaIt, PersonInfoConstant.updateArea);
                break;
            case R.id.rl_email_layout:
                if (isFromTalk) {
                    return;
                }
                Intent emailIt = new Intent(UserInfoActivity.this, EditInfoActivity.class);
                emailIt.putExtra("update_type", PersonInfoConstant.updateEmail);
                emailIt.putExtra("oldStr", tvEmail.getText().toString());
                startActivityForResult(emailIt, PersonInfoConstant.updateEmail);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUserInfoPresenter.onDestroy();
        RxBus.$().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == CHOOSE_IMAGE_REQUEST_CODE) {
            @SuppressWarnings("unchecked")
            ArrayList<PhotoItem> select_gl_arr = (ArrayList<PhotoItem>) data.getSerializableExtra("gl_arr");
            if (select_gl_arr.size() > 0) {
                for (int i = 0; i < select_gl_arr.size(); i++) {
                    String path = select_gl_arr.get(i).getPath();
                    Intent intent = new Intent(UserInfoActivity.this, ClipImageActivity.class);
                    intent.putExtra("picPath", path);
                    startActivityForResult(intent, CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE);
                }
            }

        } else if (requestCode == CHOOSE_TAKE_PHOTO_REQUEST_CODE) {
            String path = data.getStringExtra("big_pic_filename");
            Intent intent = new Intent(UserInfoActivity.this, ClipImageActivity.class);
            intent.putExtra("picPath", path);
            startActivityForResult(intent, CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE);
        } else if (requestCode == PersonInfoConstant.updateName) {
            if (tvNickname != null) {
                String result = data.getStringExtra("result");
                tvNickname.setText(result);
                RxBus.$().post(MyFragment.TAG, new CommonEvent(RxBusEventConstant.EVENT_NICK_NAME_CHANGED, result));
            }
        } else if (requestCode == PersonInfoConstant.updateEmail) {
            if (tvEmail != null)
                tvEmail.setText(data.getStringExtra("result"));
        } else if (requestCode == PersonInfoConstant.updateArea) {
            if (tvArea != null)
                tvArea.setText(data.getStringExtra("result"));
            mUserInfoPresenter.updateInfo("area", data.getStringExtra("result"));
        } else if (requestCode == CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE) {
            if (data == null) {
                return;
            }
            String pic_path = data.getStringExtra("pic_path");
            if (!TextUtils.isEmpty(pic_path)) {
                Bitmap photo = ImageUtil.CompressImageSameRadioScale(pic_path, 100, 720, 720);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.JPEG, 80, baos);

                byte[] bytes = baos.toByteArray();
                String url = APIConfiguration.getBaseUrl() + "Cust/Cust/setCustAvatar?" + APIConfiguration.getCustIdAndToken();
                mUserInfoPresenter.uploadAvatar(bytes, url);
                if (photo != null && !photo.isRecycled()) {
                    photo.recycle();
                }
            }
        }
    }
}
